<template>
  <div>
    <el-dialog title="用户组——单选" :visible="visible" width="400px" append-to-body @close="close">
      <el-input v-model="searchValue" placeholder="请输入关键字过滤" style="margin-bottom:10px" />
      <el-tag>当前用户组：{{ selectedName }}</el-tag>
      <el-tree
        ref="tree"
        :data="treeData"
        node-key="id"
        :default-expanded-keys="defaultExpandedKeys"
        :filter-node-method="filterNode"
        :expand-on-click-node="false"
        @current-change="handleTreeSelectChange"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirm">确定</el-button>
        <el-button @click="close">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {

  data() {
    return {
      visible: false,
      treeData: [],
      searchValue: '',
      defaultExpandedKeys: [],
      selectedValue: '',
      selectedName: ''
    }
  },
  watch: {
    searchValue(value) {
      this.$refs.tree.filter(value)
    }
  },
  methods: {
    show(id, name) {
      this.searchValue = ''
      this.defaultExpandedKeys = []
      this.selectedValue = id
      this.selectedName = name
      this.loadTree()
      this.visible = true
    },
    loadTree() {
      this.$api.system.userGroup.tree()
        .then(res => {
          this.treeData = res.data
          // 默认展开根节点
          this.defaultExpandedKeys.push(this.treeData[0].id)
          // 默认展开当前节点
          this.defaultExpandedKeys.push(this.selectedValue)
        })
    },
    close() {
      this.visible = false
    },
    confirm() {
      this.$emit('ok', this.selectedValue, this.selectedName)
      this.visible = false
    },
    // 树节点选中改变
    handleTreeSelectChange(data) {
      this.selectedValue = data.id
      this.selectedName = data.label
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    }

  }
}

</script>

<style scoped>
</style>
